package com.ly.aidlpratice.client

import android.annotation.SuppressLint
import android.app.Service
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.*
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.lang.ref.WeakReference
import com.ly.aidlpratice.util.logDebug

class MessengerActivity : AppCompatActivity() {

    companion object {
        const val MSG_WHAT_FROM_CLIENT_CLICK = 0
        const val MSG_WHAT_GET_CLIENT_HANDLER = 1
    }

    private val mTag: String by lazy { this::class.java.simpleName }

    private lateinit var mServiceConnect: ServiceConnection

    private lateinit var mServiceMessenger: Messenger

    internal lateinit var textView: TextView

    private var mIsConnect = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_messenger)

        mServiceConnect = object : ServiceConnection {
            override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
                logDebug(mTag, "onServiceConnected[$name]")
                service?.also {
                    mServiceMessenger = Messenger(it)
                    mIsConnect = true

                    logDebug(mTag, "send client handler to service")
                    val msg = Message.obtain()
                    //将客户端的Messenger发送给服务端，服务端就可以向客户端发送消息了
                    msg.replyTo = Messenger(ClientHandler(this@MessengerActivity))
                    msg.what = MSG_WHAT_GET_CLIENT_HANDLER
                    mServiceMessenger.send(msg)
                }
            }

            override fun onServiceDisconnected(name: ComponentName?) {
                logDebug(mTag, "onServiceDisconnected[$name]")
                mIsConnect = false
            }

        }

        textView = findViewById(R.id.textView2)
        findViewById<Button>(R.id.button5).setOnClickListener {
            if (mIsConnect) {
                logDebug(mTag, "send msg to service")
                val msg = Message.obtain()
                msg.what = MSG_WHAT_FROM_CLIENT_CLICK
                mServiceMessenger.send(msg)
            } else {
                Toast.makeText(this, "未绑定服务", Toast.LENGTH_SHORT).show()
            }
        }

        findViewById<Button>(R.id.button6).setOnClickListener {
            val intent = Intent()
            //方式一，指定包名和类名
            intent.component = ComponentName("com.ly.aidlpratice","com.ly.aidlpratice.messenger.MessengerService1")
            //方式二，在android 5.0 开始，不推荐使用隐式的绑定了，指定包名还是可以使用的
//            intent.action = "com.ly.aidlpratice.action.MESSENGER1"
//            intent.setPackage("com.ly.aidlpratice")

            //以上两种方式，都可以绑定另一个应用的服务；
            //但是在android的高版本（android 11）上，不能成功；
            //在android 8.1 上可以绑定成功
            val result = bindService(
                intent,
                mServiceConnect,
                Service.BIND_AUTO_CREATE
            )
            logDebug(mTag, "result=$result")
        }

        findViewById<Button>(R.id.button7).setOnClickListener {
            unbindService(mServiceConnect)
            mIsConnect = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mIsConnect = false
    }

    internal class ClientHandler(activity: MessengerActivity) : Handler(Looper.getMainLooper()) {

        private val mTag: String by lazy { this::class.java.simpleName }

        private var mActivity: WeakReference<MessengerActivity> = WeakReference(activity)

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            mActivity.get()?.also {
                when (msg.what) {
                    MSG_WHAT_FROM_SERVICE -> {
                        logDebug(mTag, "收到服务端发来的消息")
                        @SuppressLint("SetTextI18n")
                        it.textView.text = "随机数字：${msg.arg1}"
                    }
                }
            }
        }

        companion object {
            const val MSG_WHAT_FROM_SERVICE = 0
        }
    }
}